package com.example.pay.controller;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.example.internalcommon.request.OrderRequest;
import com.example.pay.service.AliPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author lyra
 * @Date 2023/5/6 15:42
 **/
@RequestMapping("/alipay")
@Controller
@ResponseBody
public class AlipayController {

    /**
     * 58.支付宝支付
     * @param subject
     * @param outTradeNo
     * @param totalAmount
     * @return
     */
    @GetMapping("/pay")
    public String pay(String subject, String outTradeNo, String totalAmount) {
        AlipayTradePagePayResponse response;
        try {
            response = Factory.Payment.Page().pay(subject, outTradeNo, totalAmount, "");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
        return response.getBody();
    }

    @Autowired
    AliPayService aliPayService;

    /**
     * 59.支付宝回调
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/notify")
    public String notify(HttpServletRequest request) throws Exception {
        String trade_status = request.getParameter("trade_status");
        if (trade_status.trim().equals("TRADE_SUCCESS")) {
            Map<String, String> param = new HashMap<>();
            Map<String, String[]> parameterMap = request.getParameterMap();
            for (String name : parameterMap.keySet()) {
                param.put(name, request.getParameter(name));
            }
            if (Factory.Payment.Common().verifyNotify(param)) {
                System.out.println("通过支付宝的验证");

                String out_trade_no = param.get("out_trade_no");
                long orderId = Long.parseLong(out_trade_no);

                aliPayService.pay(orderId);

            } else {
                System.out.println("支付宝验证不通过");
            }
        }
        return "success";
    }

}
